﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiDa.Domain;
using YiDa.Repository.EntityFramework.Test.Modal;
using YiDa.Repository.EntityFramework.Test.ModelConfigurations;

namespace YiDa.Repository.EntityFramework.Test
{
    public class EFTestDbContext:DbContext
    {
        public DbSet<School> Schools { get; set; }
        public DbSet<SchoolClass> SchoolClasses { get; set; }
        public DbSet<Student> Students { get; set; }

        public EFTestDbContext():base("EFTestApp")
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.LazyLoadingEnabled = true;
            this.Configuration.ValidateOnSaveEnabled = true;
            
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new SchoolTypeConfiguration())
                .Add(new SchoolClassTypeConfiguration())
                .Add(new StudentTypeConfiguration());

            base.OnModelCreating(modelBuilder);
        }

        protected override bool ShouldValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry)
        {

            return base.ShouldValidateEntity(entityEntry);
        }

        protected override DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());

            if ((entityEntry.State == System.Data.EntityState.Added || entityEntry.State == System.Data.EntityState.Modified) && entityEntry.Entity is IEntity)
            {
                if (((IEntity)entityEntry.Entity).ID == Guid.Empty)
                {
                    result.ValidationErrors.Add(new DbValidationError("ID", "在新增或修改实体时,ID属性必需赋值."));
                }
            }
            if (!result.IsValid)
            {
                return result;
            }
            return base.ValidateEntity(entityEntry, items);
        }

        public override int SaveChanges()
        {
            return base.SaveChanges();
        }
    }
}
